package com.gzy.blog.sys.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gzy.blog.sys.entity.User;
import com.gzy.blog.sys.service.UserService;

@Controller
@RequestMapping("/sys")
public class UserController {

	private static Logger log = LogManager.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@RequestMapping("/login")
	public String login(User user, HttpSession session, Model model)
			throws Exception {
		User logUser = userService.login(user);
		if (logUser != null) {
			session.setAttribute("user", logUser);
			return "redirect:/blog/initMain";
		} else {
			return "redirect:/blog/initMain";
		}
	}

	@RequestMapping("/add")
	public String add(User user) throws Exception {
		userService.add(user);
		return "redirect:/views/backstage/backstage";
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session) throws Exception {
		session.removeAttribute("user");
		return "redirect:/blog/initMain";
	}

	@RequestMapping("/delete")
	public String delete(User user) throws Exception {
		userService.delete(user);
		return "redirect:/views/backstage/backstage";
	}

	@RequestMapping("/get")
	@ResponseBody
	public User get(Integer id) throws Exception {
		System.out.println("id:" + id);
		User user = userService.get(id);
		System.out.println(user);
		return user;
	}

	@RequestMapping("/listUser")
	@ResponseBody
	public List<User> listUser() throws Exception {
		// Model model, int pageNo, int pageSize
		return userService.listUser();
	}

	@RequestMapping("/register")
	public String register(User user, HttpSession session) throws Exception {
		userService.add(user);
		session.setAttribute("user", user);
		return "views/backstage/backstage";
	}

	@RequestMapping("/update")
	public String update(User user) throws Exception {
		userService.update(user);
		return "views/backstage/backstage";
	}

}
